from flask import Blueprint
from flask import request, current_app, send_file, make_response
from http_status import HttpStatus
import utils
from flask_jwt_extended import jwt_required, get_jwt_identity
import hashlib
import os

upload_bp = Blueprint('upload', __name__)


# 设置允许的文件扩展名(圖片)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def hash_filename(filename):
    # 将文件名转换为二进制表示来生成哈希值
    hash_object = hashlib.md5(filename.encode('utf-8'))
    hashed_filename = hash_object.hexdigest()
    ext = filename.rsplit('.', 1)[1].lower()
    return f"{hashed_filename}.{ext}"

@upload_bp.route('image', methods=['POST'])
# @jwt_required()
def image():
    # user_id = get_jwt_identity()
    # 检查是否有文件被上传
    if 'file' not in request.files:
        return utils.response(success=False, message='没有文件！', status=HttpStatus.CODE_PARAM_ERROR)
    file = request.files['file']
    # 如果用户没有选择文件，浏览器可能会提交一个空的文件名
    if file.filename == '':
        return utils.response(success=False, message='没有文件！', status=HttpStatus.CODE_PARAM_ERROR)
    if file and allowed_file(file.filename):
        hashed_filename = hash_filename(file.filename)
        file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], hashed_filename))
        return utils.response(success=True, data={'filename': hashed_filename}, message='文件上传成功！', status=HttpStatus.CODE_SUECCESS)
    return utils.response(success=False, message='无效的文件类型', status=HttpStatus.CODE_PARAM_ERROR)
